package com.nondo.dean.product.controller.api.admin;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.nondo.dean.auth.common.annotation.HasUser;
import com.nondo.dean.common.annotation.ApiVersion;
import com.nondo.dean.common.domain.BaseEntity;
import com.nondo.dean.common.tool.BeanUtils;
import com.nondo.dean.common.tool.ValidateUtil;
import com.nondo.dean.common.web.Page;
import com.nondo.dean.common.web.Query;
import com.nondo.dean.common.web.View;
import com.nondo.dean.product.domain.Product;
import com.nondo.dean.product.domain.ProductAttach;
import com.nondo.dean.product.domain.ProductWithBLOBs;
import com.nondo.dean.product.model.AttachBean;
import com.nondo.dean.product.model.ProductBean;
import com.nondo.dean.product.model.param.ProductParam;
import com.nondo.dean.product.model.param.ProductQueryParam;
import com.nondo.dean.product.model.result.OrderProductResult;
import com.nondo.dean.product.model.result.ProductResult;
import com.nondo.dean.product.service.ProductAttachService;
import com.nondo.dean.product.service.ProductLogService;
import com.nondo.dean.product.service.ProductService;

/**
 * @author ken.
 * @version 1.20000
 * @email 695093513@qq.com
 * @date 2018/3/27
 */
@RestController("apiAdminProduct")
@RequestMapping("/{v}/admin/product")
public class ProductController {

    @Autowired
    ProductService productService;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    ProductLogService productLogService;

    @Autowired
    ProductAttachService productAttachService;

    /**
     * 获取产品列表
     *
     * @param request
     * @param response
     * @param query
     * @return
     */
    @ApiVersion(1)
    @RequestMapping("/list")
    public View<Page<ProductWithBLOBs>> list(HttpServletRequest request, HttpServletResponse response, @RequestBody Query<ProductParam> query) {
         View<Page<ProductWithBLOBs>> view = new View<Page<ProductWithBLOBs>>(20000, "获取数据成功");

        ProductParam productWithBLOBs = query.getData();

        Page<ProductWithBLOBs> page = new Page<ProductWithBLOBs>(query.getPage(), query.getLimit(), this.productService.count(productWithBLOBs));

        List<ProductWithBLOBs> productList = this.productService.getList(query.getOffset(), query.getLimit(), productWithBLOBs);

        page.setContent(productList);

        view.setData(page);

        return view;
    }
    
    /**
     * 更新产品
     *
     * @param request
     * @param response
     * @param productBean
     * @param result
     * @return
     */
    @HasUser
    @ApiVersion(1)
    @RequestMapping("/update")
    public View<Product> update(HttpServletRequest request, HttpServletResponse response, @Validated @RequestBody ProductBean productBean, BindingResult result) {
        View<Product> view = new View<Product>(20000, "更新成功");

        if (result.hasErrors()) {
            view.setCode(40000);
            view.setMessage(ValidateUtil.first(result.getAllErrors()));
        } else {
            
            //查询产品
            ProductWithBLOBs productWithBLOBsEntity = this.productService.selectById(productBean.getId());
            ProductWithBLOBs productWithBLOBsOrig = productWithBLOBsEntity;
            
            //处理产品属性
            if(CollectionUtils.isNotEmpty(productBean.getPropertiesList())){
                String properties = JSON.toJSONString(productBean.getPropertiesList());
                productBean.setProperties(properties);
            }
            //处理产品规格
            if(CollectionUtils.isNotEmpty(productBean.getSpecificationsList())){
                String specifications = JSON.toJSONString(productBean.getSpecificationsList());
                productBean.setSpecifications(specifications);
                JSONArray jsonArray = JSON.parseArray(specifications);
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    Integer productId = jsonObject.getInteger("productId");
                    ProductWithBLOBs productWithBLOBs = this.productService.selectById(productId);
                    productWithBLOBs.setSpecifications(specifications);
                    this.productService.update(productWithBLOBs);
                }
            }
            
            //基本赋值处理
            ProductWithBLOBs productWithBLOBs = new ProductWithBLOBs();
            BeanUtils.copy(productBean, productWithBLOBs);

            //更新基本数据
            BeanUtils.copy(productWithBLOBs, productWithBLOBsEntity);
            this.productService.update(productWithBLOBsEntity);

            //处理特殊数据
            //1、处理图片列表
            //1)、删除老的关联关系
            this.productAttachService.delete(productBean.getId());
            //2)、添加新的关联关系
            if (productBean.getAttach() != null) {
                for (AttachBean item : productBean.getAttach()) {
                    ProductAttach productAttach = new ProductAttach();
                    BeanUtils.copy(item, productAttach);
                    String path = item.getName().replaceAll("\"", "");
                    AttachBean attachBean = this.productAttachService.insertToAttach(path);
                    productAttach.setAttachId(attachBean.getId());

                    productAttach.setProductId(productBean.getId());
                    productAttach.setOrderNum(0);
                    productAttach.setDelFlag(BaseEntity.DEL_FLAG_NORMAL);
                    this.productAttachService.insert(productAttach);
                }
            }

            //写入日志
            this.productLogService.handleLog(productWithBLOBsOrig, productWithBLOBs);
        }

        return view;
    }
    
    /**
     * 产品上下架
     *
     * @param request
     * @param response
     * @param productBean
     * @param result
     * @return
     */
    @HasUser
    @ApiVersion(1)
    @RequestMapping("/update/status")
    public View<Product> updateStatus(HttpServletRequest request, HttpServletResponse response, @Validated @RequestBody ProductBean productBean, BindingResult result) {
        View<Product> view = new View<Product>(20000, "更新成功");
        ProductWithBLOBs productWithBLOBsEntity = this.productService.selectById(productBean.getId());
        productWithBLOBsEntity.setShelfStatus(productBean.getShelfStatus());
        this.productService.update(productWithBLOBsEntity);
        return view;
    }


    /**
     * 查询单个商品信息
     *
     * @param request
     * @param response
     * @param id
     * @return
     */
    @ApiVersion(1)
    @RequestMapping("/info/{id}")
    public View<Product> info(HttpServletRequest request, HttpServletResponse response, @PathVariable int id) {
        View<Product> view = new View<Product>(20000, "获取数据成功");

        ProductWithBLOBs productWithBLOBs = this.productService.findById(id);
        view.setData(productWithBLOBs);

        return view;
    }

    /**
     * 按照名称查询商品
     *
     * @param request
     * @param response
     * @param name     商品名称
     * @return 产品列表 List<{@link Product}>
     */
    @ApiVersion(1)
    @RequestMapping("/search")
    public View<List<Product>> getProductListByName(HttpServletRequest request, HttpServletResponse response, @RequestBody Product product) {
        View<List<Product>> view = new View<List<Product>>(20000, "获取数据成功");
        List<Product> productList = this.productService.getProductListByName(product.getName());
        if (productList.size() > 100){
            productList = new ArrayList<Product>();
            view.setData(productList);
            view.setCode(View.STATE_ERROR_PARAMS);
            view.setMessage("匹配产品数量太多，请调整输入名称");
            return view;
        }
        view.setData(productList);
        return view;
    }
    
    /**
     * 按照名称查询可下单商品
     *
     * @param request
     * @param response
     * @param name     商品名称
     * @return 产品列表 List<{@link OrderProductResult}>
     */
    @ApiVersion(1)
    @RequestMapping("/order/list")
    public View<List<OrderProductResult>> getOrderProductListByName(HttpServletRequest request, HttpServletResponse response,
        @RequestBody Product product) {
        View<List<OrderProductResult>> view = new View<List<OrderProductResult>>(20000, "获取数据成功");
        List<OrderProductResult> productList = this.productService.getOrderProductListByName(product.getName());
        if (productList.size() > 100){
            productList = new ArrayList<OrderProductResult>();
            view.setData(productList);
            view.setCode(View.STATE_ERROR_PARAMS);
            view.setMessage("匹配产品数量太多，请调整输入名称");
            return view;
        }
        view.setData(productList);
        return view;
    }
    
    /**
     * 根据条件查询产品基本信息
     *
     * @param request
     * @param response
     * @param query
     * @return
     */
    @ApiVersion(1)
    @RequestMapping("/query")
    public View<Page<Product>> queryList(HttpServletRequest request, HttpServletResponse response, @RequestBody Query<ProductParam> query) {
         View<Page<Product>> view = new View<Page<Product>>(20000, "获取数据成功");

        ProductParam productWithBLOBs = query.getData();

        Page<Product> page = new Page<Product>(query.getPage(), query.getLimit(), this.productService.count(productWithBLOBs));

        List<Product> productList = this.productService.getProductList(query.getOffset(), query.getLimit(), productWithBLOBs);

        page.setContent(productList);

        view.setData(page);

        return view;
    }

    /**
     * 查看某个产品的关联产品
     *
     * @param request
     * @param response
     * @param id 产品主ID
     * @return
     */
    @ApiVersion(1)
    @RequestMapping("/{id}/relative")
    public View<List<Product>> getRelativeProductListById(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Integer id) {
        View<List<Product>> view = new View<List<Product>>(20000, "获取数据成功");
        List<Product> productList = this.productService.getRelativeProductListById(id);
        view.setData(productList);
        return view;
    }
    
    /**
     * 查看某个产品的子件产品
     *
     * @param request
     * @param response
     * @param code 产品编码
     * @return
     */
    @ApiVersion(1)
    @RequestMapping("/child/list")
    public View<List<ProductResult>> getChildListByCode(HttpServletRequest request, HttpServletResponse response, @RequestBody ProductQueryParam productParam) {
        View<List<ProductResult>> view = new View<List<ProductResult>>(20000, "获取数据成功");

        if (StringUtils.isEmpty(productParam.getCode()) && StringUtils.isEmpty(productParam.getName())) {
            return View.ofParamsError("产品查询参数不能为空");
        }
        List<ProductResult> productList = this.productService.getChildListByCode(productParam);

        view.setData(productList);

        return view;
    }
}
